<template>
  <div class="addfriend-pages">
    <cp-nav-bar title="添加好友" class="addfriend-nav-bar" left-arrow> </cp-nav-bar>
    <van-cell :border="false">
      <div class="contact-item">
        <van-icon name="search" size="20" style="margin-right: 10px" />

        <span class="contact-item-search">
          <input
            type="text"
            placeholder="请输入用户名"
            class="add-friend-search"
            v-model="searchContent"
            @input="debounceInput"
          />
        </span>
      </div>
    </van-cell>
    <template v-if="searchList.length > 0">
      <van-cell v-for="data in searchList" :key="data.user_id" clickable
        ><div class="contact-item">
          <van-image
            width="38px"
            height="38px"
            fit="cover"
            radius="4px"
            :src="data.avatar"
          ></van-image>
          <span class="contact-item-text">{{ data.username }}</span>
          <van-button
            color="#16c2a3"
            size="mini"
            v-if="data.status === 'stranger'"
            @click="addFriend(data)"
            >添加好友</van-button
          >

          <van-button disabled size="mini" type="success" v-if="data.status === 'friend'"
            >已为好友</van-button
          >
          <van-button size="mini" type="success" v-if="data.status === 'requested_by_me'"
            >等待对方同意</van-button
          >
          <van-button
            size="mini"
            type="success"
            v-if="data.status === 'requested_by_other'"
            @click="acceptFriend(data)"
            >对方申请添加您为好友</van-button
          >
        </div>
      </van-cell>
    </template>
    <template v-if="searchList.length === 0 && searchContent">
      <div class="search-empty">- 搜索结果为空 -</div>
    </template>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { debounce } from 'lodash'
import { acceptFriendRequest, getSearchUser, sendFriendRequest } from '@/services/friend'
import type { SearchList } from '@/types/friend'
import { showConfirmDialog, showToast } from 'vant'

const searchContent = ref('')

const searchList = ref<SearchList[]>([])
const searchInput = async (e: Event) => {
  const inputElement = e.target as HTMLInputElement
  if (inputElement.value) {
    const res = await getSearchUser(inputElement.value)
    searchList.value = res.data
  } else {
    searchList.value = []
  }
}
const debounceInput = debounce(searchInput, 500)
const addFriend = async (data: SearchList) => {
  showConfirmDialog({
    title: '好友添加',
    message: '是否发送好友申请'
  })
    .then(async () => {
      // on confirm
      try {
        await sendFriendRequest(data.user_id, data.username, data.avatar)
        const updatedData = {
          ...data,
          status: 'requested_by_me'
        }
        searchList.value = searchList.value.map((item) => {
          if (item.user_id === updatedData.user_id) {
            return updatedData
          }
          return item
        })
        showToast('发送申请成功')
      } catch (err) {
        console.log(err)
        showToast('发送申请失败')
      }
    })
    .catch(() => {
      // on cancel
      console.log('取消好友申请')
    })
}
const acceptFriend = async (data: SearchList) => {
  showConfirmDialog({
    title: '好友申请',
    message: '是否同意好友申请'
  })
    .then(async () => {
      // on confirm
      try {
        await acceptFriendRequest(data.user_id, data.username, data.avatar)
        const updatedData = {
          ...data,
          status: 'friend'
        }
        searchList.value = searchList.value.map((item) => {
          if (item.user_id === updatedData.user_id) {
            return updatedData
          }
          return item
        })
        showToast('添加成功')
      } catch (err) {
        console.log(err)
        showToast('添加失败')
      }
    })
    .catch(() => {
      // on cancel
      console.log('取消同意')
    })
}
</script>
<style lang="scss" scoped>
.addfriend-pages {
  padding-top: 46px;
  background-color: var(--bg-primary);
  height: 100vh;
  .addfriend-nav-bar {
    background: var(--my-bg-primary);
  }
  .contact-item {
    height: 100%;
    display: flex;
    justify-content: start;
    align-items: center;
    font-size: 16px;
    color: var(--cp-contact-color);

    .contact-item-icon {
      width: 40px;
      height: 40px;
    }
    .contact-item-text {
      margin-left: 12px;
      white-space: nowrap; /* 禁止换行 */
      overflow: hidden; /* 隐藏超出部分 */
      text-overflow: ellipsis; /* 显示省略号 */
      flex: 1;
      text-align: left;
    }
    .contact-item-search {
      font-size: 16px;
      color: rgba(153, 153, 153, 1);
      margin-left: 14px;
      input {
        background-color: var(--chat-input-inset);
      }
    }
    .add-friend-search {
      border: none;
      width: 130px;
    }
  }
  .search-empty {
    text-align: center;
    margin-top: 20px;
    color: rgba(153, 153, 153, 1);
  }
}
</style>
